package apigateway.project.core.netty;

import apigateway.project.core.Config;
import apigateway.project.core.LifeCycle;
import apigateway.project.core.netty.processor.NettyProcessor;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.util.concurrent.DefaultThreadFactory;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * NettyHttpServer
 * 承接所有网络请求的核心类
 */
@Slf4j
public class NettyHttpServer implements LifeCycle {

    private NettyProcessor processor;

    private Config config;

    //服务器引导类，用于配置和启动netty
    private ServerBootstrap serverBootstrap;

    //boss线程组,用于处理新的客户端连接
    private EventLoopGroup bossGroup;
    //worker线程组，用于处理新的客户端连接
    private EventLoopGroup workerGroup;

    public NettyHttpServer(Config config, NettyProcessor processor) {
        this.config = config;
        this.processor = processor;
        init();
    }



    @Override
    public void init() {
        this.serverBootstrap = new ServerBootstrap();
        this.bossGroup = new NioEventLoopGroup(config.getEventLoopGroupBossNum(),
                new DefaultThreadFactory("default-netty-boss-nio"));
        this.workerGroup = new NioEventLoopGroup(config.getEventLoopGroupWorkerNum(),
                new DefaultThreadFactory("default-netty-worker-nio"));
    }

    @Override
    public void start() {
        this.serverBootstrap
                .group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024)            // TCP连接的最大队列长度
                .option(ChannelOption.SO_REUSEADDR, true)          // 允许端口重用
                .option(ChannelOption.SO_KEEPALIVE, true)          // 保持连接检测
                .childOption(ChannelOption.TCP_NODELAY, true)      // 禁用Nagle算法，适用于小数据即时传输
                .childOption(ChannelOption.SO_SNDBUF, 65535)       // 设置发送缓冲区大小
                .childOption(ChannelOption.SO_RCVBUF, 65535)       // 设置接收缓冲区大小
                .localAddress(new InetSocketAddress(config.getPort()))
                .childHandler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ch.pipeline().addLast(
                                new HttpServerCodec(),
                                new HttpObjectAggregator(config.getMaxContentLength()),
                                new NettyHttpServerHandler(processor)
                        );
                    }
                });
        // 绑定端口并启动服务，等待服务端关闭
        try {
            this.serverBootstrap.bind().sync();
            //也可以用这种方法进行netty端口监听的绑定
            //this.serverBootstrap.bind(config.getPort()).sync();
            log.info("server startup on port {}", this.config.getPort());
        } catch (Exception e) {
            throw new RuntimeException("启动服务器时发生异常", e);
        }
    }

    @Override
    public void shutdown() {
        if (bossGroup != null) {
            bossGroup.shutdownGracefully(); // 优雅关闭boss线程组
        }

        if (workerGroup != null) {
            workerGroup.shutdownGracefully(); // 优雅关闭worker线程组
        }
    }

    /**
     * 获取workerEventloop
     * @return
     */
    public EventLoopGroup getEventLoopWork() {
        return workerGroup;
    }
}
